import axios from 'axios';
import qs from 'qs';
import { Message,Loading } from 'element-ui';

if (!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
  }
const baseURL = window.location.origin;
const ajax = axios.create({
    baseURL,
    transformRequest:[function(data){
        const access_token = localStorage.getItem('access_token') ||'';
        const assignData = Object.assign(data,{access_token});
        return qs.stringify(assignData);
    }]
})
let loadingInstance;
ajax.interceptors.request.use(
    config=>{
        console.log(config)
        let tempConfig = config.data;
        if (tempConfig.hasOwnProperty('loading')) {
            loadingInstance = Loading.service({
              lock: true,
              text: '加载中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)',
            });
            delete tempConfig.loading;
            config.data = tempConfig ;
         }
    return config
},error=> {
    if (loadingInstance) {
        loadingInstance.close();
    }
    return Promise.reject(error)
})

ajax.interceptors.response.use(
    response=>{
        if (loadingInstance) {
            loadingInstance.close();
        }
        const {status_code,error}=response.data;
        if(status_code===10200){
            return response.data
        }else{
            Message.error(error);
            return Promise.reject(status_code+error);
        }
},err=> {
    if (loadingInstance) {
        loadingInstance.close();
    }
    const {response,request} = err;
    const {status} = request;
    if(!response){
        Message.error(`${status}:网络连接失败`);
    }
    return Promise.reject(err)
})

export default ajax;
